import React, { useEffect, useRef, useState } from "react";
import { Button, Toast, SearchBar, DotLoading, NavBar } from "antd-mobile";
import { useLocation, useNavigate } from "react-router-dom";
import { AimOutlined } from "@ant-design/icons";
import styles from "./SendAddress.module.css";

// Define types for position and AMap-related objects
interface Position {
  lng: number;
  lat: number;
}

interface Suggestion {
  name: string;
  district?: string;
  location?: {
    lng: number;
    lat: number;
  };
  [key: string]: any;
}

declare global {
  interface Window {
    AMap: any;
  }
}

const SendAddress = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const mapContainer = useRef<HTMLDivElement>(null);
  const mapInstance = useRef<any>(null);
  const [address, setAddress] = useState<string>("");
  const [position, setPosition] = useState<Position | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [searchValue, setSearchValue] = useState<string>("");
  const placeSearch = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const autoComplete = useRef<any>(null);
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [showSuggestions, setShowSuggestions] = useState<boolean>(false);
  const [isSend, setIsSend] = useState<boolean>(true);

  console.log(location);

  // 初始化地图
  useEffect(() => {
    if (location.search) {
      setIsSend(false);
    } else {
      setIsSend(true);
    }
    initMap();
    return () => {
      if (mapInstance.current) {
        mapInstance.current.destroy();
      }
    };
  }, []);

  const initMap = async () => {
    if (!window.AMap || !mapContainer.current) return;
    mapInstance.current = new window.AMap.Map(mapContainer.current, {
      center: [115.4889, 38.8149],
      resizeEnable: true,
      zoom: 16,
    });

    // 初始化 PlaceSearch 和 AutoComplete
    window.AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], () => {
      // 地点搜索插件
      placeSearch.current = new window.AMap.PlaceSearch({
        map: mapInstance.current,
        pageSize: 10,
        pageIndex: 1,
        city: "全国",
      });

      // 自动完成插件
      autoComplete.current = new window.AMap.AutoComplete({
        city: "全国",
        input: "search-input",
      });
    });

    // 监听地图点击事件
    mapInstance.current.on("click", onMapClick);
    getLocationAndClockIn();
  };

  // 处理输入变化，获取位置建议
  const handleInputChange = (value: string) => {
    setSearchValue(value);

    if (!value || !autoComplete.current) {
      setSuggestions([]);
      setShowSuggestions(false);
      return;
    }

    // 获取输入建议
    autoComplete.current.search(value, (status: string, result: any) => {
      if (status === "complete" && result.tips && result.tips.length) {
        setSuggestions(result.tips);
        setShowSuggestions(true);
      } else {
        setSuggestions([]);
        setShowSuggestions(false);
      }
    });
  };

  // 处理建议项点击
  const handleSuggestionClick = (suggestion: Suggestion) => {
    if (!suggestion || !placeSearch.current) return;

    setSearchValue(suggestion.name);
    setShowSuggestions(false);

    // 搜索选中的位置
    placeSearch.current.search(suggestion.name, (status: string, result: any) => {
      if (
        status === "complete" &&
        result.poiList &&
        result.poiList.pois.length > 0
      ) {
        const poi = result.poiList.pois[0];
        const lnglat = poi.location;

        // 设置地图中心
        mapInstance.current.setCenter([lnglat.lng, lnglat.lat]);

        // 清除旧标记并添加新标记
        if (markerRef.current) {
          mapInstance.current.remove(markerRef.current);
          markerRef.current = null;
        }

        markerRef.current = new window.AMap.Marker({
          position: [lnglat.lng, lnglat.lat],
          title: poi.name,
        });
        mapInstance.current.add(markerRef.current);

        // 更新位置和地址
        setPosition({ lng: lnglat.lng, lat: lnglat.lat });
        setAddress(poi.address || poi.name);
      } else {
        Toast.show({ icon: "fail", content: "未找到相关地点" });
      }
    });
  };

  // 搜索功能
  const handleSearch = (value: string) => {
    if (!value || !placeSearch.current) return;
    setShowSuggestions(false);

    placeSearch.current.search(value, (status: string, result: any) => {
      if (
        status === "complete" &&
        result.poiList &&
        result.poiList.pois.length > 0
      ) {
        const poi = result.poiList.pois[0];
        const lnglat = poi.location;
        mapInstance.current.setCenter([lnglat.lng, lnglat.lat]);

        // 先移除旧的 marker
        if (markerRef.current) {
          mapInstance.current.remove(markerRef.current);
          markerRef.current = null;
        }

        // 添加新 marker
        markerRef.current = new window.AMap.Marker({
          position: [lnglat.lng, lnglat.lat],
          title: poi.name,
        });
        mapInstance.current.add(markerRef.current);
        setPosition({ lng: lnglat.lng, lat: lnglat.lat });
        setAddress(poi.address || poi.name);
      } else {
        Toast.show({ icon: "fail", content: "未找到相关地点" });
      }
    });
  };

  // 地图点击事件处理
  const onMapClick = (e: any) => {
    // 关闭建议列表
    setShowSuggestions(false);

    const lnglat = e.lnglat;
    // 先移除旧的 marker
    if (markerRef.current) {
      mapInstance.current.remove(markerRef.current);
      markerRef.current = null;
    }
    // 添加新 marker
    markerRef.current = new window.AMap.Marker({
      position: [lnglat.lng, lnglat.lat],
      title: "自选位置",
    });
    mapInstance.current.add(markerRef.current);
    setPosition({ lng: lnglat.lng, lat: lnglat.lat });
    // 逆地理编码
    reverseGeocode({ lng: lnglat.lng, lat: lnglat.lat });
  };

  // 获取定位并定位
  const getLocationAndClockIn = async () => {
    setIsLoading(true);
    try {
      // 清空搜索框和建议列表
      setSearchValue("");
      setShowSuggestions(false);
      setSuggestions([]);

      // 1. 获取定位
      const position = await getCurrentPosition();

      // 2. 立即执行逆地理编码
      const currentAddress = await reverseGeocode(position);

      // 3. 添加标记
      addMarker(position);

      // 4. 设置地图中心点
      mapInstance.current?.setCenter([position.lng, position.lat]);
      // 5. 设置适当的缩放级别
      mapInstance.current?.setZoom(16);
    } catch (error) {
      handleError(error as Error);
    } finally {
      setIsLoading(false);
    }
  };

  // 获取定位
  const getCurrentPosition = (): Promise<Position> => {
    return new Promise((resolve, reject) => {
      window.AMap.plugin("AMap.Geolocation", () => {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
        });

        geolocation.getCurrentPosition((status: string, result: any) => {
          if (status === "complete") {
            setPosition(result.position);
            resolve(result.position);
          } else {
            reject(new Error(result.message));
          }
        });
      });
    });
  };

  // 错误处理
  const handleError = (error: Error) => {
    const errorMsg = error.message || "定位失败";
    Toast.show({
      icon: "fail",
      content: errorMsg,
    });
  };

  // 监听位置变化执行逆地理编码
  useEffect(() => {
    if (position) {
      reverseGeocode(position);
    }
  }, [position]);

  // 逆地理编码功能
  const reverseGeocode = async (pos: Position): Promise<string> => {
    return new Promise((resolve) => {
      window.AMap.plugin("AMap.Geocoder", () => {
        const geocoder = new window.AMap.Geocoder({ city: "全国" });

        geocoder.getAddress([pos.lng, pos.lat], (status: string, result: any) => {
          if (status === "complete" && result.info === "OK") {
            const address = result.regeocode.formattedAddress;
            setAddress(address); // 更新状态用于显示
            resolve(address); // 返回解析结果
          }
          return "";
        });
      });
    });
  };

  // 添加定位点标记
  const addMarker = (position: Position) => {
    // 先移除旧的 marker
    if (markerRef.current) {
      mapInstance.current.remove(markerRef.current);
      markerRef.current = null;
    }
    markerRef.current = new window.AMap.Marker({
      position: new window.AMap.LngLat(position.lng, position.lat),
      title: "当前位置",
    });
    mapInstance.current.add(markerRef.current);
  };

  // 发送位置
  const sendAddress = () => {
    console.log(address);
    if (isSend) {
      // 跳转到聊天界面
    } else {
      // 跳转到发送动态页面
      sessionStorage.setItem("address", address.split("市")[0] + "市");
      navigate("/add");
    }
  };

  const back = () => {
    Toast.show({
      content: "点击了返回区域",
      duration: 1000,
    });
  };

  return (
    <div className={styles.container}>
      <NavBar onBack={back}>获取位置信息</NavBar>
      {/* 搜索框与建议列表 */}
      <div className={styles.searchContainer}>
        <SearchBar
          placeholder="搜索地点"
          value={searchValue}
          onChange={handleInputChange}
          onSearch={handleSearch}
          showCancelButton
        />

        {/* 建议列表 */}
        {showSuggestions && suggestions.length > 0 && (
          <div className={styles.suggestionsList}>
            {suggestions.map((item, index) => (
              <div
                key={index}
                onClick={() => handleSuggestionClick(item)}
                className={
                  index < suggestions.length - 1
                    ? styles.suggestionItemWithBorder
                    : styles.suggestionItem
                }
              >
                <div className={styles.suggestionTitle}>{item.name}</div>
                {item.district && (
                  <div className={styles.suggestionDistrict}>
                    {item.district}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
      {/* 地图容器及悬浮按钮 */}
      <div className={styles.mapContainer}>
        <div ref={mapContainer} className={styles.mapElement} />
        {/* 右下角悬浮重新定位按钮 */}
        <div className={styles.locationButton} onClick={getLocationAndClockIn}>
          {isLoading ? (
            <DotLoading color="#666666" style={{ fontSize: "18px" }} />
          ) : (
            <AimOutlined className={styles.locationIcon} />
          )}
        </div>
      </div>
      {/* 位置信息 */}
      {position && (
        <div className={styles.addressInfo}>
          <p className={styles.addressText}>
            当前位置：
            <br />
            {address}
          </p>
        </div>
      )}
      {/* 发送位置按钮 */}
      <Button color="primary" loading={isLoading} onClick={sendAddress} block>
        {isSend ? "发送位置" : "保存地址"}
      </Button>
    </div>
  );
};

export default SendAddress;